/**
 * <p>Original Author: Daniel Freeman    http://www.danielfreeman.asia</p>
 *
 * <p>Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:</p>
 *
 * <p>The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.</p>
 *
 * <p>THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS' OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.</p>
 *
 * <p>Licensed under The MIT License</p>
 * <p>Redistributions of files must retain the above copyright notice.</p>
 * <p>You are permitted to modify and enhance this code,</p>
 * <p>As a courtesy, please credit the original author, Daniel Freeman   http://www.danielfreeman.asia</p>
 */

// Phong Shader 

package
{
	[SWF(frameRate="60")]	
	
	import com.adobe.utils.*;
	
	import flash.display.Bitmap;
	import flash.display.Sprite;
	import flash.display.Stage3D;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;
	import flash.display3D.Context3D;
	import flash.display3D.Context3DBlendFactor;
	import flash.display3D.Context3DCompareMode;
	import flash.display3D.Context3DProgramType;
	import flash.display3D.Context3DTextureFormat;
	import flash.display3D.Context3DTriangleFace;
	import flash.display3D.Context3DVertexBufferFormat;
	import flash.display3D.IndexBuffer3D;
	import flash.display3D.Program3D;
	import flash.display3D.VertexBuffer3D;
	import flash.display3D.textures.Texture;
	import flash.events.Event;
	import flash.geom.Matrix3D;
	import flash.geom.Vector3D;

	
	public class Flash3dExperimentA extends Sprite {
		
		protected static const STEPS:int = 4;
		protected static const STEPSM:int = STEPS - 1;
	
		protected static const N:int = 3;
		
		protected var _indices:Vector.<uint> = new Vector.<uint>;
		
		protected var _vertices:Vector.<Number> = new Vector.<Number>;
		
		// Usual Stage3D Stuff
		protected var _context3D:Context3D;
		protected var _shaderProgram:Program3D;
		protected var _vertexBuffer:VertexBuffer3D;
		protected var _indexBuffer:IndexBuffer3D;
		
		// Transformation Matrices
		protected var _modelMatrix:Matrix3D = new Matrix3D();
		protected var _rotationMatrix:Matrix3D;
		protected var _projectionMatrix:PerspectiveMatrix3D = new PerspectiveMatrix3D();
		
		protected var _t:Number = 0;

		public function Flash3dExperimentA(screen:Sprite = null) {
			if (screen)
				screen.addChild(this);
			
			stage.scaleMode = StageScaleMode.NO_SCALE;
			stage.align = StageAlign.TOP_LEFT;
			
			generateSphereVertices();
			generateSphereIndices();
			
			stage.stage3Ds[0].addEventListener(Event.CONTEXT3D_CREATE, onContext3DCreate);
			stage.stage3Ds[0].requestContext3D();
		}
		
		
		protected function onContext3DCreate(event:Event):void {				
			_context3D = Stage3D(event.currentTarget).context3D;
			
			if (!_context3D)
				return;
			
			_context3D.enableErrorChecking = true;
			initialiseData();
		}
		
		
		protected function generateSphereVertices():void {
			_vertices.push(0.0, -1.0, 0.0);
			for (var i:int = 0; i < STEPS; i++) {
				for (var j:int = 1; j < STEPS; j++) {
					var phi:Number = 2 * Math.PI * (i / STEPS);
					var theta:Number = Math.PI * (j / STEPS - 0.5);
					_vertices.push(
						Math.cos(theta)*Math.cos(phi),
						Math.sin(theta),
						Math.cos(theta)*Math.sin(phi)
					);
				}
			}
			_vertices.push(0.0, 1.0, 0.0);
		}
		
		
		protected function generateSphereIndices():void {
			var lastLine:int = STEPSM*STEPSM;
			for (var i:int = 0; i < STEPS; i++) {
				_indices.push(0, i*STEPSM + 1, lastLine+1);
				for (var j:int = 1; j < STEPSM; j++) {
					_indices.push(lastLine+j, i*STEPSM+j+1, lastLine+j+1);
					_indices.push(lastLine+j, i*STEPSM+j, i*STEPSM+j+1);
				}
				_indices.push(lastLine+STEPSM, (i+1)*STEPSM, _vertices.length / N - 1);
				lastLine = i * STEPSM;
			}
		}
		
		
		protected function initialiseData():void {			
			
			// Back buffer
			_context3D.configureBackBuffer(stage.stageWidth, stage.stageHeight, 1, true);
			_context3D.setCulling(Context3DTriangleFace.FRONT);
			
			// Upload Indexes
			_indexBuffer = _context3D.createIndexBuffer( _indices.length );
			_indexBuffer.uploadFromVector(_indices, 0, _indices.length );
			
			// Upload vertex data
			_vertexBuffer = _context3D.createVertexBuffer( _vertices.length/N, N); 
			_vertexBuffer.uploadFromVector(_vertices, 0, _vertices.length/N);
			
			// A simple vertex shader which does a 3D transformation
			var vertexShaderAssembler:AGALMiniAssembler = new AGALMiniAssembler();
			vertexShaderAssembler.assemble( Context3DProgramType.VERTEX,
				// 4x4 matrix multiply
				"m44 v0, va1, vc4 \n" +		// rotate vertex to derive normal
				"m44 op, va0, vc0 \n"		// translate vertex
			);
			
			// A simple fragment shader which will use the vertex position as a colour
			var fragmentShaderAssembler:AGALMiniAssembler = new AGALMiniAssembler();
			fragmentShaderAssembler.assemble( Context3DProgramType.FRAGMENT,
				"nrm ft0.xyz, v0 \n" +					// normalise normal
				"mov ft0.w, fc0.w \n" +					// set the w component to 1
				
				"dp3 ft0.x, ft0, fc0 \n" +				// dot product between normal and half-angle
				"sat ft0.x, ft0.x \n" +					// clip value between 0 and 1
				
				"pow ft1.x, ft0.x, fc3.w \n" +			// raise dot product to power
				
				"mul ft2.xyz, fc2.xyz, ft0.xxx \n" +	// diffuse colour x (dot product)
				"add ft2.xyz, fc1.xyz, ft2.xyz \n" +	// add ambient colour
				
				"mul ft3.xyz, fc3.xyz, ft1.xxx \n" +	// specular colour x (dot product) ^ power
				
				"add oc, ft2.xyz, ft3.xyz"				// combine and output
			);
			
			// Combine shaders then upload to the GPU
			_shaderProgram = _context3D.createProgram();
			_shaderProgram.upload( vertexShaderAssembler.agalcode, fragmentShaderAssembler.agalcode);
			
			// Perspective transformation
			_projectionMatrix.perspectiveFieldOfViewLH(45.0*Math.PI/180,stage.stageWidth/stage.stageHeight,0.1,1000.0);
			
			// Start animating
			addEventListener(Event.ENTER_FRAME,enterFrame);
		}
		
		
		protected function normalise4(p:Number, q:Number, r:Number, quotient:Number = 0):Vector.<Number> {
			if (quotient==0)
				quotient = Math.sqrt(p * p + q * q + r * r);
			return Vector.<Number>([ p/quotient, q/quotient, r/quotient, 1.0 ]);
		}
		
		
		protected function enterFrame(event:Event):void {
			_context3D.clear();

			_context3D.setVertexBufferAt( 0, _vertexBuffer,  0, Context3DVertexBufferFormat.FLOAT_3 );
			_context3D.setVertexBufferAt( 1, _vertexBuffer,  0, Context3DVertexBufferFormat.FLOAT_3 );
			
			_context3D.setProgram ( _shaderProgram );
			
			//Update rotation
			_modelMatrix.identity();
			_modelMatrix.appendRotation(_t*0.7, Vector3D.Y_AXIS);
			_modelMatrix.appendRotation(_t*0.6, Vector3D.X_AXIS);
			_modelMatrix.appendRotation(_t*1.0, Vector3D.Z_AXIS);
			_rotationMatrix = _modelMatrix.clone();
			
			_modelMatrix.appendScale(0.5, 0.5, 0.5);
			_modelMatrix.appendTranslation(0, 0, 2);
			_modelMatrix.append(_projectionMatrix);
			
			_t+=4.0;
			
			_context3D.setProgramConstantsFromMatrix(Context3DProgramType.VERTEX, 0, _modelMatrix, true);		// va0 - va3
			_context3D.setProgramConstantsFromMatrix(Context3DProgramType.VERTEX, 4, _rotationMatrix, true);	// va4 - va7
			
			_context3D.setProgramConstantsFromVector(Context3DProgramType.FRAGMENT, 0, normalise4(2, 1, -3) );							// fc1 Half Angle Vector
			_context3D.setProgramConstantsFromVector(Context3DProgramType.FRAGMENT, 1, Vector.<Number>([ 0.1, 0.1, 0.2, 1.0 ]) ); // fc2 Ambient Colour
			_context3D.setProgramConstantsFromVector(Context3DProgramType.FRAGMENT, 2, Vector.<Number>([ 0.3, 0.3, 0.3, 1.0 ]) ); // fc3 Diffuse Colour
			_context3D.setProgramConstantsFromVector(Context3DProgramType.FRAGMENT, 3, Vector.<Number>([ 0.5, 0.5, 0.5, 50.0 ]) );	// fc4 Specular Colour
			
			_context3D.drawTriangles( _indexBuffer);
			
			_context3D.present();
		}

	}
}